/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "maya_local.h"

#define CG_CALL(call) do { call; CheckError(); } while (0);

/*-----------------------------------------------------------------------------
	Shader system :
-----------------------------------------------------------------------------*/

EMShaderSystem::EMShaderSystem()
{
	context	=	cgCreateContext();

	vs_prof	=	cgGLGetLatestProfile(CG_GL_VERTEX);
	gs_prof	=	cgGLGetLatestProfile(CG_GL_GEOMETRY);
	ps_prof	=	cgGLGetLatestProfile(CG_GL_FRAGMENT);
	
	shell->AddCommand("reloadShaders", (EShellCmd_f)ReloadShaders_f, this);

	LOGF("Cg vertex program   : %s\r\n",	cgGetProfileString(vs_prof));
	LOGF("Cg geometry program : %s\r\n",	cgGetProfileString(gs_prof));
	LOGF("Cg pixel program    : %s\r\n",	cgGetProfileString(ps_prof));
}


EMShaderSystem::~EMShaderSystem()
{
	for (uint i=0; i<shader_sources.size(); i++) {
		delete shader_sources[i];
	}
	shader_sources.clear();
}


void EMShaderSystem::DisableShaders(void)
{
	cgGLUnbindProgram(ps_prof);
	cgGLUnbindProgram(vs_prof);
	
	cgGLDisableProfile(ps_prof);
	cgGLDisableProfile(vs_prof);
}


EMShaderSource *EMShaderSystem::RegisterShader(const char *path)
{
	for (uint i=0;i<shader_sources.size(); i++) {
		if ( strcmp(shader_sources[i]->Path(), path)==0 ) {
			return shader_sources[i];
		}
	}
	
	EMShaderSource *src = new EMShaderSource(path, this);
	shader_sources.push_back(src);
	
	return src;
}


void EMShaderSystem::ReloadShaders_f(EMShaderSystem *self, int argc, char **argv)
{
	for (uint i=0; i<self->shader_sources.size(); i++) {
		self->shader_sources[i]->CleanShaders();
	}
}


/*-----------------------------------------------------------------------------
	Shader source :
-----------------------------------------------------------------------------*/

//
//	EMShaderSource::EMShaderSource
//
EMShaderSource::EMShaderSource(const char *path, EMShaderSystem *shader_sys)
{
	this->source_path	=	path;
	this->shader_sys	=	shader_sys;
	vs_prof		=	shader_sys->VertexProfile();
	gs_prof		=	shader_sys->GeomProfile();
	ps_prof		=	shader_sys->PixelProfile();
	context		=	shader_sys->Context();
	CleanShaders();
}


//
//	EMShaderSource::~EMShaderSource
//	
EMShaderSource::~EMShaderSource(void)
{
	CleanShaders();		
}


//
//	EMShaderSource::CleanShaders
//
void EMShaderSource::CleanShaders(void)
{
	for (uint i=0; i<ps_list.size(); i++) {
		delete ps_list[i];
	}
	for (uint i=0; i<gs_list.size(); i++) {
		delete gs_list[i];
	}
	for (uint i=0; i<vs_list.size(); i++) {
		delete vs_list[i];
	}
	ps_list.clear();
	vs_list.clear();
	gs_list.clear();
	
	current_gs = NULL; 
	current_vs = NULL; 
	current_ps = NULL;
}


//
//	EMShaderSource::SetDefine
//	
void EMShaderSource::SetDefine(uint64_t bit, const char *def)
{
	if (!IsPOT(bit)) {
		LOGF(va("%X is not power of two", bit));
		return;
	}

	uint bit_pos = GetBitPosition(bit);
	definitions[bit_pos] = def;
}


//
//	EMShaderSource::Path
//
const char *EMShaderSource::Path(void)
{
	return source_path.c_str();
}


//
//	EMShaderSource::SetVertexShader
//	
void EMShaderSource::SetVertexShader(uint64_t bits, bool compile_only)
{
}


//
//	EMShaderSource::SetGeomShader
//
void EMShaderSource::SetGeomShader(uint64_t bits, bool compile_only)
{
}


//
//	EMShaderSource::SetPixelShader
//
void EMShaderSource::SetPixelShader(uint64_t bits, bool compile_only)
{
	EMShader_s *shader = NULL;
	
	for (uint i=0; i<ps_list.size(); i++) {
		if (ps_list[i]->def_bits==bits) {
			shader = ps_list[i];
			break;
		}
	}
	
	if (!shader) {
		vector<string>	defs;
		defs.push_back("CG");
		defs.push_back("PIXEL_SHADER");

		shader = CompileShader(ps_prof, "PSMain", bits, defs);
		ps_list.push_back(shader);
		
		CG_CALL( cgGLLoadProgram(shader->program) );
	}

	if (!compile_only) {	
		CG_CALL( cgGLEnableProfile(ps_prof) );
		CG_CALL( cgGLBindProgram(shader->program) );
	}
	
	current_ps = shader;
}


//
//	EMShaderSource::CompileShader
//
EMShader_s *EMShaderSource::CompileShader(CGprofile prof, const char *entry, uint64_t bits, vector<string> &add_defs)
{
	vector<string> args_strs;
	vector<const char*> args_ptrs;
	
	for (uint i=0; i<add_defs.size(); i++) {
		string arg;
		arg += "-D";
		arg += add_defs[i];
		arg += "=1 ";
		args_strs.push_back(arg);
	}
	
	for (uint i=0; i<64; i++) {
		string arg;
		uint64_t bit = (uint64_t)1 << i;
		if (bit & bits) {
			arg += "-D";
			arg += definitions[i];
			args_strs.push_back(arg);
		}
	}

	for (uint i=0; i<args_strs.size(); i++) {	
		args_ptrs.push_back( args_strs[i].c_str() );
	}
	args_ptrs.push_back(NULL);
	
	
	LOGF("compiling : %s\r\n", source_path.c_str());

	EMShader_s	*shader =	new EMShader_s;
	shader->def_bits	=	bits;
	shader->program		=	cgCreateProgramFromFile(context, CG_SOURCE, source_path.c_str(), ps_prof, entry, &args_ptrs[0]);
	CheckError();
	
	return shader;
}


//
//	EMShaderSource::SetPSConst
//
void EMShaderSource::SetPSConst(const char *name, const EVec4 &v)
{
	if (!current_ps) {
		return; 
	}
	
	CGparameter p = cgGetNamedParameter(current_ps->program, name);
	if (!cgIsParameter(p)) {
		return;
	}
	CheckError();
	
	cgGLSetParameter4fv(p, v.v);
	CheckError();
}




/*-----------------------------------------------------------------------------
	Utils :
-----------------------------------------------------------------------------*/

//
//	EMShaderSource::CheckError
//										  
void EMShaderSource::CheckError(void)
{
	CGerror error;
	const char *string = cgGetLastErrorString(&error);
	
	if (error==CG_INVALID_ENUMERANT_ERROR) {	//	Maya`s bug
		return;
	}

	if (error != CG_NO_ERROR) {
		if (error == CG_COMPILER_ERROR) {
			LOGF("%s\n", cgGetLastListing(context));
		} else {
			LOGF("%s\n", string);
		}
	}		
}






